#include "address_ui_logic.h"
#include <QFormLayout>
#include "UserSession.h"
AddressLogic::AddressLogic(AddressUI *ui, QObject *parent)
    : QObject(parent), ui(ui)
{
    connect(ui->addAddressButton, &QPushButton::clicked, this, &AddressLogic::onAddAddressClicked);


    getAddressBook();

}

void AddressLogic::setupAddressData()
{
    //
}

void AddressLogic::parseAddressAndCreateWidgets(int row, const QString &address)
{
    QLabel *nameLabel = new QLabel("收件人：");
    QLabel *phoneLabel = new QLabel("手机号：");
    QLabel *areaLabel = new QLabel("姓名：：");
    QLabel *detailLabel = new QLabel("详细地址：");
    QCheckBox *defaultCheckbox = new QCheckBox("设置为默认地址");
    QPushButton *editButton = new QPushButton("修改");
    QPushButton *deleteButton = new QPushButton("删除");

    ui->gridLayout->addWidget(nameLabel, row, 0);
    ui->gridLayout->addWidget(phoneLabel, row, 1);
    ui->gridLayout->addWidget(areaLabel, row, 2);
    ui->gridLayout->addWidget(detailLabel, row, 3);
    ui->gridLayout->addWidget(defaultCheckbox, row, 4);
    ui->gridLayout->addWidget(editButton, row, 5);
    ui->gridLayout->addWidget(deleteButton, row, 6);

    connect(editButton, &QPushButton::clicked, [this, row]()
            { onEditAddressClicked(row); });
    connect(deleteButton, &QPushButton::clicked, [this, row]()
            { onDeleteAddressClicked(row); });

    QStringList details = address.split(", ");
    nameLabel->setText(details[0]);
    phoneLabel->setText(details[1]);
    areaLabel->setText(details[2]);
    detailLabel->setText(details[3]);
   getAddressBook();
}
void AddressLogic::parseAddressAndCreateWidgets(int row, const QString &address, int addressId)
{
    QLabel *nameLabel = new QLabel("标签：");
    QLabel *phoneLabel = new QLabel("手机号：");
    QLabel *usernameLabel = new QLabel("姓名：");
    QLabel *detailLabel = new QLabel("详细地址：");
    QCheckBox *defaultCheckbox = new QCheckBox("设置为默认地址");
    QPushButton *editButton = new QPushButton("修改");
    QPushButton *deleteButton = new QPushButton("删除");
    ui->gridLayout->addWidget(nameLabel, row, 0);
    ui->gridLayout->addWidget(phoneLabel, row, 1);
    ui->gridLayout->addWidget(usernameLabel, row, 2);
    ui->gridLayout->addWidget(detailLabel, row, 3);
    ui->gridLayout->addWidget(defaultCheckbox, row, 4);
    ui->gridLayout->addWidget(editButton, row, 5);
    ui->gridLayout->addWidget(deleteButton, row, 6);

    connect(editButton, &QPushButton::clicked, [this, row]()
            { onEditAddressClicked(row); });
    connect(deleteButton, &QPushButton::clicked, [this, row]()
            { onDeleteAddressClicked(row); });

    QStringList details = address.split(",");
    nameLabel->setText(details[0]);
    usernameLabel->setText(details[1]);
    phoneLabel->setText(details[2]);
    detailLabel->setText(details[3]);
    QLabel *idLabel = new QLabel("id");
    idLabel->setText(QString::number(addressId)); // 将地址ID转为字符串
    idLabel->setVisible(false);                   // 隐藏这个标签
    idLabel->setProperty("addressId", addressId);
    ui->gridLayout->addWidget(idLabel, row, 7);


}
void AddressLogic::onAddResponseReceived(PptpMessage response)
{
    QJsonObject responseParameters = response.getParameters();
    qDebug() << "服务器响应:" << responseParameters;

    QString message = responseParameters.value("message").toString(); // 假设返回的消息字段
    bool success = responseParameters.value("isOK").toBool();
    if (success)
    {
        QMessageBox::information(nullptr, "成功", message);
    }
    else
    {
        QMessageBox::warning(nullptr, "失败", message);
    }
}

void AddressLogic::onAddAddressClicked()
{
    QDialog *dialog = new QDialog;
    dialog->setWindowTitle("添加地址");
    QVBoxLayout *layout = new QVBoxLayout(dialog);
    QRadioButton *homeButton = new QRadioButton("家");
    QRadioButton *companyButton = new QRadioButton("公司");
    QRadioButton *schoolButton = new QRadioButton("学校");

    // 将单选按钮放入一个ButtonGroup中，使其成为互斥的
    QButtonGroup *group = new QButtonGroup(dialog);
    group->addButton(homeButton);
    group->addButton(companyButton);
    group->addButton(schoolButton);
    QHBoxLayout *radioLayout = new QHBoxLayout;
    radioLayout->addWidget(homeButton);
    radioLayout->addWidget(companyButton);
    radioLayout->addWidget(schoolButton);
    layout->addLayout(radioLayout);
    QLabel *nameLabel = new QLabel("收件人姓名:");
    QLineEdit *nameEdit = new QLineEdit;
    layout->addWidget(nameLabel);
    layout->addWidget(nameEdit);
    QLabel *phoneLabel = new QLabel("收件人电话:");
    QLineEdit *phoneEdit = new QLineEdit;
    layout->addWidget(phoneLabel);
    layout->addWidget(phoneEdit);
    QLabel *addressLabel = new QLabel("详细地址:");
    QLineEdit *addressEdit = new QLineEdit;
    layout->addWidget(addressLabel);
    layout->addWidget(addressEdit);
    QPushButton *saveButton = new QPushButton("保存");
    layout->addWidget(saveButton);
    connect(saveButton, &QPushButton::clicked, dialog, [=]()
            {
                QString type;
                if (homeButton->isChecked())
                {
                    type = "家";
                }
                else if (companyButton->isChecked())
                {
                    type = "公司";
                }
                else if (schoolButton->isChecked())
                {
                    type = "学校";
                }

                QString name = nameEdit->text();
                QString phone = phoneEdit->text();
                QString address = addressEdit->text();

                qDebug() << "地址类型:" << type;
                qDebug() << "收件人:" << name;
                qDebug() << "电话:" << phone;
                qDebug() << "地址:" << address;

                PptpMessage requestMessage;
                QJsonObject parameters;
                parameters["label"] = type;
                parameters["name"] = name;
                parameters["phone"] = phone;
                parameters["address"] = address;
                parameters["userId"] = UserSession::getInstance().getUserId();
                requestMessage.clear();
                requestMessage.setParameters(parameters);
                requestMessage.setPath("user/addAddress");
                pptpclient.pptpConnect(IP, PORT, requestMessage, this, &AddressLogic::onAddResponseReceived);
                dialog->accept();
                // 调用parseAddressAndCreateWidgets显示新添加的地址
                QString fullAddress = QString("%1, %2, %3, %4").arg(name, phone, type, address);
                int row = ui->gridLayout->rowCount();           // 获取当前行数以便插入
                parseAddressAndCreateWidgets(row, fullAddress); // 传递详细信息以创建地址控件
            });

    dialog->exec();
}
void AddressLogic::getAddressBook()
{
    PptpMessage requestMessage;
    requestMessage.clear();
    int userId = UserSession::getInstance().getUserId();
    QJsonObject parameters;
    parameters["userId"] = userId;
    requestMessage.clear();
    requestMessage.setParameters(parameters);
    qDebug() << parameters;
    requestMessage.setPath("user/getAddressBook");
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &AddressLogic::onGetAddressBookResponse);
}
void AddressLogic::onGetAddressBookResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug() << "获取的信息" << responseParameters;
    QJsonArray addressBookArray = responseParameters.value("addressBook").toArray();

    QLayoutItem *item;
    while ((item = ui->gridLayout->takeAt(7)) != nullptr)
    {
        delete item->widget(); // 删除 widget
        delete item;           // 删除布局项
    }

    for (int i = 0; i < addressBookArray.size(); ++i)
    {
        QJsonObject addressObject = addressBookArray[i].toObject();
        int addressId = addressObject.value("addressId").toInt();
        QString label = addressObject.value("label").toString();
        QString name = addressObject.value("name").toString();
        QString phone = addressObject.value("phone").toString();
        QString detailAddress = addressObject.value("detailAddress").toString();
        QString fullAddress = QString("%1, %2, %3, %4").arg(label, name, phone, detailAddress);
        int row = ui->gridLayout->rowCount();
        parseAddressAndCreateWidgets(row, fullAddress, addressId);
    }
}

void AddressLogic::onEditAddressClicked(int row)
{

    QLabel *idLabel = qobject_cast<QLabel *>(
        ui->gridLayout->itemAtPosition(row, 7)->widget()); // Assuming idLabel is in column 7
    if (!idLabel)
    {
        qDebug() << "ID label not found!";
        return;
    }

    int addressId = idLabel->property("addressId").toInt();

    QWidget *widget0 = ui->gridLayout->itemAtPosition(row, 0)->widget();
    QWidget *widget1 = ui->gridLayout->itemAtPosition(row, 1)->widget();
    QWidget *widget2 = ui->gridLayout->itemAtPosition(row, 2)->widget();
    QWidget *widget3 = ui->gridLayout->itemAtPosition(row, 3)->widget();

    // 检查是否为QLabel类型
    QLabel *oldlabel = qobject_cast<QLabel *>(widget0);
    QLabel *oldphone = qobject_cast<QLabel *>(widget1);
    QLabel *oldname = qobject_cast<QLabel *>(widget2);
    QLabel *oldaddress = qobject_cast<QLabel *>(widget3);
    if (!oldlabel || !oldphone || !oldname || !oldaddress)
    {
        qDebug() << "One or more labels not found!";
        return;
    }

    // 创建对话框
    QDialog editDialog;
    editDialog.setWindowTitle(tr("编辑框"));

    // 创建主布局
    QVBoxLayout *dialogLayout = new QVBoxLayout(&editDialog);

    // 创建表单布局来组织标签和输入框
    QFormLayout *formLayout = new QFormLayout;

    // 创建输入框来显示旧数据并允许编辑
    QLineEdit *nameEdit = new QLineEdit(oldname->text(), &editDialog);
    QLineEdit *phoneEdit = new QLineEdit(oldphone->text(), &editDialog);
    QLineEdit *addressEdit = new QLineEdit(oldaddress->text(), &editDialog);
    formLayout->addRow(tr("姓名:"), nameEdit);
    formLayout->addRow(tr("手机号:"), phoneEdit);
    formLayout->addRow(tr("详细地址:"), addressEdit);
    QRadioButton *homeButton = new QRadioButton(tr("家"));
    QRadioButton *schoolButton = new QRadioButton(tr("学校"));
    QRadioButton *companyButton = new QRadioButton(tr("公司"));
    QButtonGroup *radioButtonGroup = new QButtonGroup(&editDialog);
    radioButtonGroup->addButton(homeButton);
    radioButtonGroup->addButton(schoolButton);
    radioButtonGroup->addButton(companyButton);
    QHBoxLayout *radioButtonLayout = new QHBoxLayout;
    radioButtonLayout->addWidget(homeButton);
    radioButtonLayout->addWidget(schoolButton);
    radioButtonLayout->addWidget(companyButton);
    formLayout->addRow(tr("标签:"), radioButtonLayout);
    QPushButton *saveButton = new QPushButton(tr("保存"), &editDialog);
    dialogLayout->addLayout(formLayout);
    dialogLayout->addWidget(saveButton);
    connect(saveButton, &QPushButton::clicked, [&]()
            {
        QString newName = nameEdit->text();
        QString newPhone = phoneEdit->text();
        QString newAddress = addressEdit->text();

        QString type;
        if (homeButton->isChecked()) {
            type = "家";
        } else if (companyButton->isChecked()) {
            type = "公司";
        } else if (schoolButton->isChecked()) {
            type = "学校";
        }

        PptpMessage requestMessage;
        QJsonObject parameters;
        parameters["addressId"] = addressId;
        parameters["name"] = newName;
        parameters["phone"] = newPhone;
        parameters["address"] = newAddress;
        parameters["label"] = type; // 添加类型字段
        requestMessage.setParameters(parameters);
        requestMessage.setPath("user/editAddress");

        qDebug() << "Edit Address Parameters: " << parameters;

        // 发送请求到后端
        pptpclient.pptpConnect(IP, PORT, requestMessage, this, &AddressLogic::onEditAddressResponse);

        // 关闭编辑对话框
        editDialog.accept(); });

    // 显示编辑窗口
    editDialog.exec();
}

void AddressLogic::onEditAddressResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    bool success = responseParameters.value("isOK").toBool(); // Check if the edit was successful

    if (success)
    {
        QMessageBox::information(nullptr, "编辑成功", "地址信息已成功修改。");
        getAddressBook();
    }
    else
    {
        QMessageBox::warning(nullptr, "编辑失败", "地址信息修改失败，请重试。");
    }
}

void AddressLogic::onDeleteAddressResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    bool success = responseParameters.value("isOK").toBool(); // Check if the deletion was successful

    if (success)
    {
        QMessageBox::information(nullptr, "删除成功", "地址已成功删除。");
        for (int col = 0; col < ui->gridLayout->columnCount(); ++col)
        {
            QWidget *widget = ui->gridLayout->itemAtPosition(currentRow, col)->widget();
            if (widget)
            {
                delete widget; // Delete the widget to free memory
            }
        }

        // Remove the layout item for the row (not the row itself, since QGridLayout does not support removeRow)
        for (int col = 0; col < ui->gridLayout->columnCount(); ++col)
        {
            QLayoutItem *item = ui->gridLayout->itemAtPosition(currentRow, col);
            if (item)
            {
                ui->gridLayout->removeItem(item);
            }
        }
    }
    else
    {
        QMessageBox::warning(nullptr, "删除失败", "地址删除失败，请重试。");
    }
}
void AddressLogic::onDeleteAddressClicked(int row)
{
    currentRow = row;
    QLabel *idLabel = qobject_cast<QLabel *>(
        ui->gridLayout->itemAtPosition(row, 7)->widget()); // Assuming idLabel is in column 7
    if (!idLabel)
    {
        qDebug() << "ID label not found!";
        return;
    }
    int addressId = idLabel->property("addressId").toInt();
    PptpMessage requestMessage;
    QJsonObject parameters;
    parameters["addressId"] = addressId;
    requestMessage.clear();
    requestMessage.setParameters(parameters);
    requestMessage.setPath("user/deleteAddress");
    qDebug() << "delete" << parameters;
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &AddressLogic::onDeleteAddressResponse);
}

AddressLogic::~AddressLogic() {}
